package cn.lzm.basic.config;

import cn.lzm.basic.util.AjaxResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice /*作用是给Controller控制器添加统一的操作或处理 自定义AOP 里面携带AOP的必要属性*/
public class AdviceController {


    @ResponseBody
    @ExceptionHandler /*用于捕获Controller中抛出的指定类型的异常，从而达到不同类型的异常区别处理的目的*/
    public AjaxResult processException(Exception ex) {

        AjaxResult result ;
//        if (ex instanceof ApiException) {
//            ApiException error = (ApiException) ex;
//            result= AjaxResult.me().fail(error.getMessage());
//        }else
        if (ex instanceof MethodArgumentNotValidException){/*instanceof 属于*/
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
            result= AjaxResult.me().fail(exception.getBindingResult().getFieldError().getDefaultMessage());
        }else if (ex instanceof BussinessException){
            BussinessException bex = (BussinessException) ex;
            result = AjaxResult.me().fail(bex.getMessage());
        }
        else {
            ex.printStackTrace();
            result = AjaxResult.me().fail();
        }
        return result;

    }
}